package org.elsfs.auth.service;

import org.elsfs.domain.entity.SysUser;
import org.elsfs.domain.manager.SysUserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.stereotype.Service;

/**
 * {@link UserDetailsService} 适配器
 *
 * @author zeng
 * @since 0.0.1
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired private SysUserManager sysUserManager;
  private UserCache userCache = new NullUserCache();

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails details = userCache.getUserFromCache(username);
    if (details != null) {
      return details;
    }
    SysUser sysUser = sysUserManager.getUserByUsername(username);
    if (sysUser != null) {
      details = userDetails(sysUser);
      userCache.putUserInCache(details);
      return details;
    }
    throw new UsernameNotFoundException("用户不存在");
  }

  private UserDetails userDetails(SysUser sysUser) {
    return new UserDetailsImpl(sysUser, AuthorityUtils.createAuthorityList("admin"));
  }
}
